//
//  DiaryFile.m
//  VideoDiaryClass
//
//  Created by Wang Haitao on 15/10/19.
//  Copyright © 2015年 qianfeng. All rights reserved.
//

#import "DiaryFile.h"

@interface DiaryFile ()

@property (nonatomic) NSMutableArray * data;
@property (nonatomic) NSString * path;

@end

@implementation DiaryFile

+ (DiaryFile *) sharedInstance
{
    __strong static DiaryFile * diaryFile = nil;
    if (diaryFile) {
        return diaryFile;
    }
    
    static dispatch_once_t d;
    
    dispatch_once(&d, ^{
        diaryFile = [DiaryFile new];
    });
    
    return diaryFile;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        self.path = [paths[0] stringByAppendingPathComponent:@"VideoDiary.plist"];
        
        [self load];
    }
    return self;
}

- (void) load
{
    NSData * data = [NSData dataWithContentsOfFile:self.path];
    self.data = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    if (!self.data) {
        self.data = [NSMutableArray new];
    }
}

- (void) save
{
    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:self.data];
    [data writeToFile:self.path atomically:YES];
}

- (void) addDiary: (Diary *)diary
{
    NSInteger type = 0;
    
    if (self.data.count!=0) {
        Diary * diary0 = [self.data firstObject];
        type = diary0.type==0 ? 1 : 0;
    }
    diary.type = type;
    
    [self.data insertObject:diary atIndex:0];
    [self save];
}

- (NSUInteger) diaryCount
{
    return self.data.count;
}

- (Diary *) diaryAtIndex: (NSUInteger) index
{
    if (index>=self.data.count) {
        return nil;
    }
    return self.data[index];
}

- (void) removeDiary: (Diary *) diary
{
    [diary clear];
    [self.data removeObject:diary];
    [self save];
}

- (void) removeDiaryAtIndex: (NSUInteger) index
{
    Diary * diary = [self diaryAtIndex:index];
    if (diary) {
        [self removeDiary:diary];
    }
}


@end
